#!/bin/bash

umask 0077
# 返回码
declare -i ret_ok=0                                     # 成功
declare -i ret_failed_dictionary_no_space=1             # 失败 文件夹空间不够
declare -i ret_failed_soft_has_installed=2              # 失败 软件已安装
declare -i ret_failed_copy_file_failed=3                # 失败 拷贝文件失败
declare -i ret_failed_create_config_file_failed=4       # 失败 配置文件创建失败
declare -i ret_failed_arg_install_dir_failed=5          # 失败 安装目录参数错误
declare -i ret_failed_arg_log_dir_failed=6              # 失败 日志目录参数错误
declare -i ret_failed_dir_permission_denied=7           # 失败 目录权限受限
declare -i ret_failed_group_id_not_root=8               # 失败 用户组非root权限，必须为root权限
declare -i ret_failed_command_not_exist=9               # 失败 命令不存在

SOFTWARE_NAME="AtlasEdge"        # 安装路径的头子目录

DEFAULT_WORK_DIR="/usr/local"
WORK_DIR=""
WORK_PATH=""

ATLAS_EDGE_CONFIG_FILE="config.ini"

ATLAS_EDGE_NODE_INFO="NODE_INFO"

SITE_SCRIPT_DIR="software/edge_site/edge_manager/src/script"
ATLAS_EDGE_ELABLE_INFO="/run/elabel_info"
CORE_CONFIG_FILE="software/edge_core/conf/edgecore.yaml"
MODELFILE_DIR="/var/lib/docker/modelfile/"

path=$(cd $(dirname $0); pwd)
cd ${path}
CURRENT_PATH=${path}

InstallForceFlag="0"  #强制升级待调试 如何处理运行程序

#默认安装模式
INSTALL_TYPE="Typical"
# 默认厂商
DEFAULT_MANUFACTURER="huawei"
# 默认设备类型
DEFAULT_PRODUCT_TYPE="Atlas 200"

# 默认网管模式
DEFAULT_NETMANAGER="Web"

# 默认ha路径 Full安装模式生效
DEFAULT_HA_WORK_PATH=""

# 默认参数值
DEFAULT_VALUE=""

. ./${SITE_SCRIPT_DIR}/common.sh

function usage()
{
    echo "input like:  ./install.sh  --install_dir=xxx --log_dir=xxx"
}

DEFAULT_LOG_DIR="/var/alog"
LOG_DIR=""
LOG_FILE=atlasedge_script.log

init_log_path() {
    LOG_PATH="$LOG_DIR/AtlasEdge_log/"
    UpgradgeLog="$LOG_PATH/$LOG_FILE"
    if [ ! -d ${LOG_PATH} ]; then
        mkdir -p ${LOG_PATH} && chmod -R 700 ${LOG_PATH}
    fi
    if [ ! -f ${LOG_PATH}/${LOG_FILE} ]; then
        touch ${LOG_PATH}/${LOG_FILE} && chmod 600 ${LOG_PATH}/${LOG_FILE}
    fi
}

if [ -t 1 ] && [ "1$(tput colors 2>/dev/null)" -ge 18 ]; then
  readonly color_red="$(tput setaf 1)"
  readonly color_yellow="$(tput setaf 3)"
  readonly color_green="$(tput setaf 2)"
  readonly color_norm="$(tput sgr0)"
else 
  readonly color_red=""
  readonly color_yellow=""
  readonly color_green=""
  readonly color_norm=""
fi

if command -v caller >/dev/null 2>&1; then
  # return func(lineno:filename)
  # NOTE: skip 2-level inner frame
  _caller() { caller 2| awk '{sub(/.*\//,e,$3);print $2"("$3":"$1") "}'; }
else
  _caller() { :; }
fi

_log() 
{
    level=$1
    shift 1
    if [ -f "${UpgradgeLog}" ]; then
        local cur_user=$(whoami)
        if [ ${cur_user} == "HwHiAiUser" ]; then
          echo "$(date ${date_format})-${level}-$(_caller)- $*" >> ${UpgradgeLog}
        else
          sudo -u HwHiAiUser bash -c "echo '$(date ${date_format})-${level}-$(_caller)- $*' >> ${UpgradgeLog}" 2>/dev/null
        fi
    fi
    echo "$(date ${date_format})-${level}-$(_caller)- $*"
}

logger_Debug() 
{
    echo "$(date ${date_format})-${level}- $*"
}

logger_Info() 
{
  _log INFO "$@"
}

logger_Warn() 
{
  _log WARN "${color_yellow}$*${color_norm}"
}

logger_Error() 
{
  _log ERROR "${color_red}$*${color_norm}"
}


# 检查权限是否为root组
check_root_group() {
    local effective_gid=$(id | grep -o "gid=[0-9]*" | cut -d= -f2)

    if [ $effective_gid -ne 0 ]
    then
        logger_Warn "The script needs to be run as root group."
        return 1;
    fi
}

# 检测docker是否存在
check_docker_exist() {
    if docker ps 2>/dev/null | grep -q IMAGE && ls -l /var/run/docker.sock >/dev/null 2>&1 ;then
        logger_Debug "docker has already exists"
    else
        logger_Error "docker must be installed on this device, please check."
        return 1
    fi
}

#检查环境包括：命令 文件夹内存 等
function precheck() {
    if [ -z "$WORK_DIR" ]; then
        logger_Info "install dir user default $(basename ${DEFAULT_WORK_DIR})"
        WORK_DIR=$DEFAULT_WORK_DIR
        if [ ! -d $WORK_DIR ];then
            mkdir -p $WORK_DIR
            chmod 700 $WORK_DIR
        fi
    elif [ ! -d "$WORK_DIR" ]; then
        logger_Warn "install dir $(basename ${WORK_DIR}) not exist. exit"
        return $ret_failed_arg_install_dir_failed;
    fi

    # 检测空间是否满足要求 300M
    requestSpace=307200
    availSpace=$(df "$WORK_DIR" | awk 'NR==2 { print $4 }')
    logger_Debug "avalidSpace:" ${availSpace} "requestSpace:" ${requestSpace}
    if [ ${availSpace} -lt ${requestSpace} ]; then
        logger_Warn "$(basename ${WORK_DIR}) not enough Space avalid:" ${availSpace} " need:" ${requestSpace}
        return ${ret_failed_dictionary_no_space}
    fi

    # 检测是否为root组权限
    check_root_group
    ret=$?
    if [ ${ret} -ne 0 ]; then
        logger_Warn "install precheck failed not root group ret:" $ret
        return ${ret_failed_group_id_not_root}
    fi

    check_all_commands
    ret=$?
    if [ ${ret} -ne 0 ]; then
        logger_Warn "install precheck failed cmd not find ret:" $ret
        return ${ret_failed_command_not_exist}
    fi

    if [ "$IGNORE_DOCKER_STATUS_CHECK" != "1" ];then 
        check_docker_exist
        ret=$?
        if [ ${ret} -ne 0 ]; then
            logger_Warn "install precheck failed docker cmd not active ret:" $ret
            return ${ret_failed_command_not_exist}
        fi
    fi

    containerinfo=`docker ps -a -q`
    modelfileCount=`ls -l $MODELFILE_DIR 2>/dev/null | grep "^d" | wc -l`
    if [ "$containerinfo" != "" -o $modelfileCount -ne 0 ];then
        logger_Debug "Notice: There may be containers or modelfiles remain in $(basename ${MODELFILE_DIR}). Please clear them if you don't need anymore"
    fi

    if [ "$containerinfo" != "" ];then
        logger_Debug "Notice: Docker service will be restarted later and the running containers will exit and be removed"
    fi

    logger_Debug "install preCheck OK "
    return 0
}

#创建工作目录
function create_work_dir() {

    # 检查安装和日志目录区读写执行权限是否OK
    if [ -r "${LOG_DIR}" -a -w "${LOG_DIR}" -a -r "${WORK_DIR}" -a -w "${WORK_DIR}"  ]; then
        logger_Debug "dir access is OK "
    else
        logger_Warn "install or log dir access failed"
        return ${ret_failed_dir_permission_denied}
    fi

    #更新工作目录，增加软件名目录
    WORK_PATH=${WORK_DIR}/${SOFTWARE_NAME}
    LOG_PATH=${LOG_DIR}/${SOFTWARE_NAME}_log

    #如果当前目录下已经存在bin和conf uninstall.sh，那么认为已经安装过了，退出安装
    if [ -e "${WORK_PATH}/bin" -o -e "${WORK_PATH}/config" -o -e "${WORK_PATH}/uninstall.sh" ]; then
        if [ ${InstallForceFlag} -eq 0 ]; then
            logger_Warn "${SOFTWARE_NAME} has been installed. please uninstall or remove the installed path (${WORK_PATH}) firstly"
            return ${ret_failed_soft_has_installed}
        fi
    fi

    #创建日志目录 如果不存在就新建  存在不删除
    if [ ! -d ${LOG_PATH} ]; then
        mkdir -p ${LOG_PATH} && chmod -R 700 ${LOG_PATH}
    fi

    #创建工作目录
    if [ -d ${WORK_PATH} ]; then
        rm -rf ${WORK_PATH}
    fi
    mkdir -p ${WORK_PATH} && chmod -R 700 ${WORK_PATH}

    # 创建software目录
    if [ -d ${WORK_PATH}/software ]; then
        rm -rf ${WORK_PATH}/software
    fi
    mkdir -p ${WORK_PATH}/software
    chmod -R 700 ${WORK_PATH}/software
    
    # 创建配置目录
    if [ -d ${WORK_PATH}/config ]; then
        rm -rf ${WORK_PATH}/config
    fi
    mkdir -p ${WORK_PATH}/config
    chmod -R 700 ${WORK_PATH}/config

    return 0
}

#填充系统信息
fill_sys_info(){

    check_command_exist dmidecode
    dmidecode_exist=$?

    # get productName from dmidecode
    if [[ ${dmidecode_exist} == 0 ]]; then
        ProductName=`dmidecode  -t1 | grep "Product Name:" | sed 's/^.*Product Name:[ \t]//'`
        if [[ "${ProductName}" !=  "" ]]; then
            DEFAULT_PRODUCT_TYPE=${ProductName}
        else
            # Atlas200 and Atlas500 not support dmidecode command,
            # determine the Atlas 500 through find "brd_t=sei" in /proc/cmdline
            grep -q brd_t=sei /proc/cmdline 2>/dev/null
            if [[ $? == 0 ]]; then
                DEFAULT_PRODUCT_TYPE="Atlas 500"
            fi
        fi
    fi

    # write DevMgmtType
    WriteDevMgmtTypeToYaml ${WORK_PATH}/${CORE_CONFIG_FILE} "${DEFAULT_PRODUCT_TYPE}"


    # 待完善 文件信息获取失败待讨论
    asset_tag=""
    if [ -f $ATLAS_EDGE_ELABLE_INFO ]; then
        serial_num=`cat $ATLAS_EDGE_ELABLE_INFO |grep "prd_serial_num" | awk '{print $2}'`
        asset_tag=`cat $ATLAS_EDGE_ELABLE_INFO |grep "extend_info" | awk '{print $2}'`
    fi

    # 序列号获取失败 从dmidecode中尝试获取
    if [ "${serial_num}" ==  "" -a $dmidecode_exist == 0 ]; then
        BMCType=`cat ${WORK_PATH}/${CORE_CONFIG_FILE} | grep devMgmtType | awk '{print $2}'`
        if [ "$BMCType" == "BMC" ]; then
            serial_num=`dmidecode -t1 | grep "Serial Number:" | awk -F ":" '{print $2}' | awk '$1=$1'`
        else
            serial_num=`dmidecode -t2 | grep "Serial Number:" | awk -F ":" '{print $2}' | awk '$1=$1'`
        fi
    fi

    rand_serial=`cat /proc/sys/kernel/random/uuid`
    sed -i "s|nodeId:.*|nodeId: ${rand_serial}|g" ${WORK_PATH}/${CORE_CONFIG_FILE}

    if [ "${serial_num}" == "" -o "${serial_num}" == "Not Specified" -o "${serial_num}" == "Default string" ]; then
        logger_Info "slable info not exist or no serail_num:"$(basename ${ATLAS_EDGE_ELABLE_INFO}) "use random serial"  $rand_serial
        sed -i "s|serialNumber:.*|serialNumber: ${rand_serial} |g" ${WORK_PATH}/${CORE_CONFIG_FILE}
    else
        sed -i "s|serialNumber:.*|serialNumber: ${serial_num}|g" ${WORK_PATH}/${CORE_CONFIG_FILE}
    fi

    update_interface_name ${CORE_CONFIG_FILE}

    # get manufacturer from dmidecode
    if [ $dmidecode_exist == 0 ]; then
        manufacturer=`dmidecode -t1 | grep "Manufacturer:" | awk '{print $2}'`
        if [ "${manufacturer}" !=  "" ]; then
            if [ "${manufacturer}" ==  "Huawei" ]; then
                DEFAULT_MANUFACTURER="huawei"
            else
                DEFAULT_MANUFACTURER=$manufacturer
            fi
        fi
    fi

    return 0
}

# 更新脚本或者配置信息PATH等信息
flush_path_info(){
    # 更新配置
    sed -i "s|{work_path}|${WORK_PATH}|g" ${WORK_PATH}/software/edge_site/edge_manager/config/atlasedge.service
    
    sed -i "s|{work_path}|${WORK_PATH}|g" ${WORK_PATH}/run.sh
    sed -i "s|{script_path}|${WORK_PATH}/${SITE_SCRIPT_DIR}|g" ${WORK_PATH}/run.sh

    sed -i "s|{work_path}|${WORK_PATH}|g" ${WORK_PATH}/${SITE_SCRIPT_DIR}/uninstall.sh
    sed -i "s|{script_path}|${WORK_PATH}/${SITE_SCRIPT_DIR}|g" ${WORK_PATH}/${SITE_SCRIPT_DIR}/uninstall.sh

    sed -i "s|{work_path}|${WORK_PATH}|g" ${WORK_PATH}/${SITE_SCRIPT_DIR}/config.sh
    sed -i "s|{script_path}|${WORK_PATH}/${SITE_SCRIPT_DIR}|g" ${WORK_PATH}/${SITE_SCRIPT_DIR}/config.sh

    sed -i "s|{service_path}|${WORK_PATH}/software/edge_site/edge_manager/config|g" ${WORK_PATH}/${SITE_SCRIPT_DIR}/start.sh
    sed -i "s|{script_path}|${WORK_PATH}/${SITE_SCRIPT_DIR}|g" ${WORK_PATH}/${SITE_SCRIPT_DIR}/start.sh
    sed -i "s|{work_path}|${WORK_PATH}|g" ${WORK_PATH}/${SITE_SCRIPT_DIR}/start.sh

    sed -i "s|{work_path}|${WORK_PATH}|g" ${WORK_PATH}/${SITE_SCRIPT_DIR}/stop.sh
    sed -i "s|{script_path}|${WORK_PATH}/${SITE_SCRIPT_DIR}|g" ${WORK_PATH}/${SITE_SCRIPT_DIR}/stop.sh

    sed -i "s|{work_path}|${WORK_PATH}|g" ${WORK_PATH}/${SITE_SCRIPT_DIR}/upgrade.sh
    sed -i "s|{script_path}|${WORK_PATH}/${SITE_SCRIPT_DIR}|g" ${WORK_PATH}/${SITE_SCRIPT_DIR}/upgrade.sh

    sed -i "s|{log_path}|${LOG_PATH}|g" ${WORK_PATH}/software/edge_site/common/log/logging.cfg

    sed -i "s|{log_path}|${LOG_PATH}|g" ${WORK_PATH}/${SITE_SCRIPT_DIR}/log_util.sh
    sed -i "s|{log_path}|${LOG_PATH}|g" ${WORK_PATH}/${SITE_SCRIPT_DIR}/mdw_log_retate_by_size.sh

    sed -i "s|loggerFile:[^)]*|loggerFile: \"${LOG_PATH}/cloud_operation.log\"|g" ${WORK_PATH}/software/edge_core/conf/oprLogging.yaml

    sed -i "s|{work_path}|${WORK_PATH}|g" ${WORK_PATH}/${SITE_SCRIPT_DIR}/update_workkey.sh
    sed -i "s|{script_path}|${WORK_PATH}/${SITE_SCRIPT_DIR}|g" ${WORK_PATH}/${SITE_SCRIPT_DIR}/update_workkey.sh

    sed -i "s|{work_path}|${WORK_PATH}|g" ${WORK_PATH}/software/edge_site/ha_handler/scripts/config_hahandler.sh

    sed -i "s|{work_path}|${WORK_PATH}|g" ${WORK_PATH}/${SITE_SCRIPT_DIR}/config_resume.sh
    sed -i "s|{script_path}|${WORK_PATH}/${SITE_SCRIPT_DIR}|g" ${WORK_PATH}/${SITE_SCRIPT_DIR}/config_resume.sh
    
    sed -i "s|{work_path}|${WORK_PATH}|g" ${WORK_PATH}/${SITE_SCRIPT_DIR}/mod_backup.sh
    sed -i "s|{script_path}|${WORK_PATH}/${SITE_SCRIPT_DIR}|g" ${WORK_PATH}/${SITE_SCRIPT_DIR}/mod_backup.sh

    sed -i "s|{work_path}|${WORK_PATH}|g" ${WORK_PATH}/${SITE_SCRIPT_DIR}/ha_status_monitor.sh

    sed -i "s|{work_path}|${WORK_PATH}|g" ${WORK_PATH}/${SITE_SCRIPT_DIR}/mod_file_list.txt
    sed -i "s|{script_path}|${WORK_PATH}/${SITE_SCRIPT_DIR}|g" ${WORK_PATH}/${SITE_SCRIPT_DIR}/mod_file_list.txt

    sed -i "s|{work_path}|${WORK_PATH}|g" ${WORK_PATH}/${SITE_SCRIPT_DIR}/updateCRL.sh
    sed -i "s|{script_path}|${WORK_PATH}/${SITE_SCRIPT_DIR}|g" ${WORK_PATH}/${SITE_SCRIPT_DIR}/updateCRL.sh
    
    sed -i "s|{work_path}|${WORK_PATH}|g" ${WORK_PATH}/${SITE_SCRIPT_DIR}/update_software_CRL.sh
    sed -i "s|{script_path}|${WORK_PATH}/${SITE_SCRIPT_DIR}|g" ${WORK_PATH}/${SITE_SCRIPT_DIR}/update_software_CRL.sh
}

#拷贝文件到工作目录
function copy_file_to_work_dir() {
    # 出错信息是否到 配置文件中 如果拷贝出错 待完善 ！！
    cp -rf ${CURRENT_PATH}/software  ${WORK_PATH}/
    if [ "$?" != "0" ]; then
        logger_Warn "copy bin file  failed"
        return ${ret_failed_copy_file_failed};
    fi

    # Atlas 500 场景下已存在密钥材料，需要平滑，不能覆盖
    if [ ! -d "/home/data/" ];then
        mkdir -p /home/data/ && chmod 755 /home/data/
        cp -arf ${CURRENT_PATH}/software/cert_key/config /home/data/
        if [ "$?" != "0" ]; then
            logger_Warn "copy file failed"
            return ${ret_failed_copy_file_failed};
        fi
    else
        if [ ! -d "/home/data/config" ];then
            cp -arf ${CURRENT_PATH}/software/cert_key/config /home/data/
            if [ "$?" != "0" ]; then
                logger_Warn "copy file failed"
                return ${ret_failed_copy_file_failed};
            fi
        fi
    fi

    # 拷贝版本信息文件
    cp -rf ${CURRENT_PATH}/version.xml  ${WORK_PATH}/
    if [ "$?" != "0" ]; then
        logger_Warn "copy file failed"
        return ${ret_failed_copy_file_failed};
    fi

    # 移动
    mv -f ${WORK_PATH}/${SITE_SCRIPT_DIR}/edge_main.sh  ${WORK_PATH}/
    mv -f ${WORK_PATH}/${SITE_SCRIPT_DIR}/edge_upd_effect.sh  ${WORK_PATH}/
    mv -f ${WORK_PATH}/${SITE_SCRIPT_DIR}/run.sh  ${WORK_PATH}/
    if [ "$?" != "0" ]; then
        logger_Warn "mv file failed"
        return ${ret_failed_copy_file_failed};
    fi

    chmod -R 700 ${WORK_PATH}/edge_main.sh
    chmod -R 700 ${WORK_PATH}/edge_upd_effect.sh
    chmod -R 700 ${WORK_PATH}/run.sh
    if [ "$?" != "0" ]; then
        logger_Warn "chmod file failed"
        return ${ret_failed_copy_file_failed};
    fi

    # 刷新路径信息
    flush_path_info
    if [ "$?" != "0" ]; then
        logger_Warn "copy flush path info failed"
        return ${ret_failed_copy_file_failed};
    fi

    #获取系统参数信息
    fill_sys_info

    # set install plugin info
    set_install_type ${INSTALL_TYPE} ${WORK_PATH}

    return ${ret_ok}
}

function create_config_file() {
    # 是否需要做该动作 多余？
    if [ ! -d ${WORK_PATH}/config ]; then
        mkdir -p ${WORK_PATH}/config
    fi
    chmod -R 700  ${WORK_PATH}/config

    # 创建默认配置文件 填充默认值
    if [ ! -f ${WORK_PATH}/config/${ATLAS_EDGE_CONFIG_FILE} ]; then
        cat > ${WORK_PATH}/config/${ATLAS_EDGE_CONFIG_FILE} <<EOF
[SYS]
install_dir=${WORK_PATH}
log_path=${LOG_PATH}
install_type=${INSTALL_TYPE}
ha_work_path=${DEFAULT_HA_WORK_PATH}
user_log_path=${DEFAULT_VALUE}
collect_log_size=${DEFAULT_VALUE}
model_file_size=${DEFAULT_VALUE}

EOF
    else
        logger_Warn "config file has exist"
        return ${ret_failed_create_config_file_failed}
    fi
    chmod 600 ${WORK_PATH}/config/${ATLAS_EDGE_CONFIG_FILE}
    # 创建默认配置文件 填充默认值
    if [ ! -f ${WORK_PATH}/config/${ATLAS_EDGE_NODE_INFO} ]; then
        cat > ${WORK_PATH}/config/${ATLAS_EDGE_NODE_INFO} <<EOF
node_type: ${DEFAULT_PRODUCT_TYPE}
net_manager: ${DEFAULT_NETMANAGER}
lib_name: websocket_FD.so
manufacturer: ${DEFAULT_MANUFACTURER}

EOF
    else
        logger_Warn "config file has exist"
        return ${ret_failed_create_config_file_failed}
    fi
    chmod 600 ${WORK_PATH}/config/${ATLAS_EDGE_NODE_INFO}
	chmod 400 ${WORK_PATH}/software/edge_core/certFD/FD.crt
    sha256sum ${WORK_PATH}/software/edge_core/certFD/FD.crt > ${WORK_PATH}/software/edge_core/certFD/FD_Backup.checksum
    if [ -e /etc/redhat-release ] && [ ! -e /etc/lsb-release ]; then  
        cp -f ${WORK_PATH}/software/edge_core/certFD/FD.crt /etc/pki/ca-trust/source/anchors/
        sha256sum /etc/pki/ca-trust/source/anchors/FD.crt > ${WORK_PATH}/software/edge_core/certFD/FD_Work.checksum
        chmod 400 /etc/pki/ca-trust/source/anchors/FD.crt
        update-ca-trust extract
        certPath="/etc/pki/ca-trust/source/anchors/FD.crt"
        sed -i "s|tlsCaFile:.*|tlsCaFile: ${certPath} |g" ${WORK_PATH}/${CORE_CONFIG_FILE}
    else
        update-ca-certificates
        cp -f ${WORK_PATH}/software/edge_core/certFD/FD.crt /usr/local/share/ca-certificates/
        sha256sum /usr/local/share/ca-certificates/FD.crt > ${WORK_PATH}/software/edge_core/certFD/FD_Work.checksum
        chmod 400 /usr/local/share/ca-certificates/FD.crt
        update-ca-certificates
        certPath="/usr/local/share/ca-certificates/FD.crt"
        sed -i "s|tlsCaFile:.*|tlsCaFile: ${certPath} |g" ${WORK_PATH}/${CORE_CONFIG_FILE}
    fi

    if [ -e /usr/bin/docker ]; then
        service docker restart
    fi

    if [ ! -f ${WORK_PATH}/config/modelfiles.json ]; then
        echo {} >> ${WORK_PATH}/config/modelfiles.json
        chmod 600 ${WORK_PATH}/config/modelfiles.json
    fi
    if [ ! -f ${WORK_PATH}/config/user_set_capablity.json ]; then
        echo {} >> ${WORK_PATH}/config/user_set_capablity.json
        chmod 600 ${WORK_PATH}/config/user_set_capablity.json
    fi

    return ${ret_ok}
}

function update_ha_config()
{
    product_name=$(dmidecode -t1 | grep "Product Name")
    if [[ "$product_name" == *Atlas\ 500\ Pro* ]]; then
        export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:${WORK_PATH}/software/lib/
        export PYTHONPATH=$PYTHONPATH:${WORK_PATH}/software/edge_site/
        export ATLASEDGE_WORK_PATH=${WORK_PATH}
        export ATLASEDGE_CONFIG_PATH=${WORK_PATH}/config
        export ATLASEDGE_SOFTWARE_PATH=${WORK_PATH}/software
        $(type -p python3) ${WORK_PATH}/software/edge_site/edge_manager/src/python/config_capability.py ha_config enable
    fi
}

function config_hw_user_group() {
    # check HwHiAiUser user and group exist
    HW_USER="HwHiAiUser"
    HW_GROUP="HwHiAiUser"
    HW_HOME=/home/HwHiAiUser
    egrep "^$HW_GROUP" /etc/group >&/dev/null || groupadd $HW_GROUP
    egrep "^$HW_USER" /etc/passwd >&/dev/null || useradd -g $HW_GROUP $HW_USER -s "$(type -p nologin)"
    [ ! -d ${HW_HOME} ] && mkdir -p ${HW_HOME} && chown $HW_USER:$HW_GROUP ${HW_HOME} && chmod 700 ${HW_HOME}
}

# 实际安装命令 执行 预检测 目录创建 文件拷贝 配置文件创建等操作
function do_install()
{
    # 配置HW用户组
    config_hw_user_group
    # 预检测 判断是否满足安装条件
    precheck;
    ret=$?
    if [ ${ret} -ne 0 ]; then
        logger_Error "install precheck failed"
        return ${ret}
    fi

    # 创建工作目录
    create_work_dir
    ret=$?
    if [ $ret != 0 ];then
        logger_Warn "Install create workDir failed"
        return $ret
    fi

    # 拷贝文件到工作目录
    copy_file_to_work_dir
    ret=$?
    if [ $ret != 0 ];then
        logger_Warn "Install copyFile failed"
        return $ret
    fi

    # 创建配置文件
   create_config_file
   ret=$?
    if [ $ret != 0 ];then
        logger_Warn "Install create Config failed"
        return $ret
    fi

    # set file soft link
    set_file_link $WORK_PATH
    ret=$?
    if [ $ret != 0 ];then
        logger_Warn "Install set file link failed"
        return $ret
    fi

    update_ha_config
    chown "HwHiAiUser:HwHiAiUser" "${WORK_PATH}" -R

    logger_Info "install OK"
    return $ret_ok
}

function clear_work_env(){
    
    if [ ! "$WORK_PATH" = "" ];then
        rm -rf ${WORK_PATH}
    fi
}

function main()
{
    # init log path info
    LOG_DIR=$DEFAULT_LOG_DIR
    if [ ! -d $LOG_DIR ];then
        mkdir -p $LOG_DIR
        chmod 700 $LOG_DIR
    fi
    init_log_path

    ARGS=`getopt -o h -a -l help,install_dir:,log_dir:,ignore_docker_status_check -n "install.sh" -- "$@"`
    if [ $? != 0 ]
    then
        logger_Warn "arg error $@"
        exit 1
    fi
    eval set -- "$ARGS"

    while true
    do
        case "$1" in
            --install_dir | -install_dir)
                WORK_DIR=$(readlink -f $2)
                shift 2
                ;;
            --log_dir | -log_dir)
                if [ "$2" != "" -a -d "$2" ];then
                    LOG_DIR=$(readlink -f $2)
                    init_log_path
                else
                    logger_Warn "install failed log dir [$2] not exist. exit:$ret_failed_arg_log_dir_failed"
                    exit $ret_failed_arg_log_dir_failed
                fi
                shift 2
                ;;
            --ignore_docker_status_check)
                IGNORE_DOCKER_STATUS_CHECK=1
                shift
                ;;
            -h|--help)
                usage
                exit 1
                ;;
            --)
                shift
                break
                ;;
            *) 
                logger_Warn "Internal error! $@"
                exit 1
                ;;
            esac
    
    done

    #执行安装命令
    do_install
    ret=$?
    if [ ${ret} != 0 ];then
        logger_Error "Install failed"

        if [ ${ret} != $ret_failed_soft_has_installed ];then
            # 安装失败 清理环境
            clear_work_env
            logger_Info "clean path file"
        fi

        return ${ret}
    fi

    # set install file user, group and permission
    bash ${WORK_PATH}/${SITE_SCRIPT_DIR}/privilege_config.sh ${WORK_PATH} ${LOG_PATH} /home/data/config > /dev/null 2>&1
    logger_Info "set install file user, group and permission finish, ret:$?"

    return 0
}

main "$@"
RESULT=$?
logger_Info "install install_DIR:"$(basename ${WORK_DIR}) "LOG_DIR:"$(basename ${LOG_DIR}) "RET : "$RESULT
exit $RESULT
